#include "XThreadPool.h"
#include "XThread.h"
#include "XTask.h"
#include "LogWrapper.h"
#include <thread>


XThreadPool::XThreadPool()
{
}

void  XThreadPool::init(int threadCount)
{
	mThreadCount = threadCount;
	for (int i = 0; i < threadCount; i++) {
		XThread *thread = new XThread;
		thread->mId = i + 1;
        LOG_DEBUG("Create thread {}", i);
		mThreads.push_back(thread);
		thread->start();
		std::this_thread::sleep_for(std::chrono::milliseconds(10));
	}
}

void XThreadPool::dispatch(XTask * task)
{
	do {
		if (!task) {
			break;
		}
		int tid = (mLastThread + 1) % mThreadCount;
		mLastThread = tid;
		XThread *t = mThreads[tid];
        t->addTask(task);
		t->activate();
	} while (0);
}

XThreadPool::~XThreadPool()
{
    for (XThread *thread : mThreads) {
        delete thread;
    }
    mThreads.clear();
}